﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Threading;

namespace SerialPortReceiveTest
{
        class Program
        {
                private static SerialPort sp = new SerialPort("COM2", 9600, Parity.None, 8, StopBits.One);

                static void Main(string[] args)
                {
                        Console.WriteLine("Open COM2");
                        sp.Open();

                        sp.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(SerialPort_DataReceived);

                        Console.WriteLine("Send Query,waiting receive....");
                        byte[] command = new byte[] { 0XFF, 0X5F,0X0A,0X69, 0X55};
                        sp.Write(command, 0, 5);

                        Thread.Sleep(50);

                        Console.ReadKey();
                }

                static void SerialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
                {
                        if (sp.BytesToRead < 1)
                        {
                                return;
                        }

                        byte[] buffer = new byte[sp.BytesToRead];
                        sp.Read(buffer, 0, buffer.Length);

                        foreach (var item in buffer)
                        {
                                Console.Write("{0:X}",item);
                                Console.WriteLine();
                        }
                }
        }
}
